
package com.heima.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urllist = new ArrayList<>();

    // 初始化白名单 url  路径
    static {
        urllist.add("/login/in");
        urllist.add("/v2/api-docs");
    }

    /**
     * @param exchange: 封装请求的上下文  request  response
     * @param chain:    过滤器链  可以放行请求
     * @return
     */


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径  判断路径是否属于白名单路径
        String path = request.getURI().getPath();
        for (String allowUri : urllist) {
            //如果白名单属于单路径 直接放行请求
            if(path.contains(allowUri)){
                return chain.filter(exchange);
            }
        }
        //获取请求头中的token的值
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            //如果没有token 终止请求  返回401状态
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
            // return writeMessage(exchange,"未携带token")；
        }

        //校验token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            // -1 有效  0 有效 1 过期  2 过期
            int i = AppJwtUtil.verifyToken(claims);
            if (i < 1) {
                //如果token有效   获取token中的userId
                Object id = claims.get("id");
                //要想修改request必须先调用mutate方法
                // 并且将userId 设置到请求头中   路由给其他微服务  放行请求
                request.mutate().header("userId", String.valueOf(id));
                // 放行请求
                return chain.filter(exchange);
            } else {
                log.error("token已经失效");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析token失败了");
        }
        //如果token无效   终止请求  返回401状态
        response.setStatusCode(HttpStatus.UNAUTHORIZED);

        return response.setComplete();

        // return writeMessage(exchange,"token解析失败")；
    }


    // 返回错误信息
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
